<template>
  <smart-table
    ref="mainTable"
    :title="problemTitle"
    :formList="problemFormList"
    :selectUrl="problemSelectUrl"
    :insertUrl="problemInsertUrl"
    :updateUrl="problemUpdateUrl"
    :deleteUrl="problemDeleteUrl"
    :detailUrl="problemDetailUrl"
    :exportExcelUrl="problemExportUrl"
    :importExcelUrl="problemImportUrl"
    :tableColumns="problemTableColumns"
    :formButtonCtl="problemFormButtonCtl"
    :formRules="problemFormRules"
    :dialogWidth="60"
    :openDialogMethodExtend="initData"
    :dialogLabelWidth="labelWidth"
    :maxOptionButtonCount="4">
    <!-- 详情 -->
    <template slot="dialog-custom-detail-item" slot-scope="item">
      <template v-if="item.item.item.name == 'answer'">
        <el-descriptions-item :label="item.item.item.title" v-if="item.item.optionFormData.type >= 3">
          <v-md-editor mode="preview" v-model="item.item.optionFormData[item.item.item.name]" height="250px"></v-md-editor>
        </el-descriptions-item>
        <el-descriptions-item v-else :label="item.item.item.title"
          ><el-descriptions direction="horizontal" column="1"
            ><el-descriptions-item v-for="option in item.item.optionFormData.options" :key="`option${option.index}`" :label="`选项${option.index}`">
              <el-input v-model="option.content" :class="option.isAnswer ? 'success_answer' : 'error_answer'">
                <template slot="prepend">
                  <el-switch v-model="option.isAnswer" active-color="#13ce66" inactive-color="#ff4949"> </el-switch>
                </template>
              </el-input> </el-descriptions-item></el-descriptions
        ></el-descriptions-item>
      </template>
    </template>
    <!-- 弹窗动态部分 -->
    <template slot="dialog-custom-form-item" slot-scope="item">
      <!-- 客观题部分 -->
      <template v-if="item.item.optionFormData.type < 3 && item.item.item.name == 'answer'">
        <el-form-item :label-width="`${labelWidth}%`"
          ><el-button type="success" icon="el-icon-plus" size="mini" @click="addOption(item.item.optionFormData)">新增选项</el-button></el-form-item
        >
        <el-form-item
          v-for="(option, index) in item.item.optionFormData.options"
          :prop="`options.${index}.content`"
          :key="`option${option.index}`"
          :label="`选项${option.index}`"
          :rules="problemFormRules.option"
          :label-width="`${labelWidth}%`">
          <el-input v-model="option.content" clearable>
            <template slot="prepend">
              <el-switch
                active-color="#13ce66"
                inactive-color="#ff4949"
                v-model="option.isAnswer"
                @change="optionChange(option, item.item.optionFormData)"
                >答案</el-switch
              >
            </template>
            <template slot="append">
              <el-button type="danger" icon="el-icon-delete" @click="deleteOption(index, item.item.optionFormData)">删除</el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>
      <!-- 主观题 -->
      <template v-else>
        <el-form-item :label-width="`${labelWidth}%`" :key="item.item.item.name" :prop="item.item.item.name" :label="item.item.item.title">
          <v-md-editor
            :height="'height' in item.item.item ? item.item.item.height : '400px'"
            v-model="item.item.optionFormData[item.item.item.name]"
            :placeholder="`请输入${item.item.item.title}`"
            @upload-image="markdownUploadFile"
            :disabled-menus="[]"></v-md-editor>
        </el-form-item>
      </template>
    </template>
  </smart-table>
</template>

<script>
import { downloadFile } from '@/utils/file'
export default {
  data() {
    return {
      labelWidth: 10,
      //主题
      problemTitle: '试题',
      //表单数据
      problemFormData: {},
      //表单列表
      problemFormList: [
        {
          title: '试题内容',
          name: 'content',
          type: 'markdown',
        },
        {
          title: '分数',
          name: 'score',
          type: 'number',
          numberRange: {
            min: 1,
            max: 100,
          },
          hidden: {
            header: true,
          },
        },
        {
          title: '科目',
          name: 'subjectName',
          hidden: {
            insertDialog: true,
            updateDialog: true,
            header: true,
          },
        },
        {
          title: '题库',
          name: 'bankId',
          type: 'select',
          optionList: [],
          showValue: false,
          hidden: {
            detailDialog: true,
            header: true,
          },
        },
        {
          title: '题库',
          name: 'bankName',
          hidden: {
            insertDialog: true,
            updateDialog: true,
            header: true,
          },
        },
        {
          title: '科目',
          name: 'subjectId',
          type: 'select',
          optionList: [],
          key: 'id',
          label: 'name',
          showValue: false,
          hidden: {
            detailDialog: true,
          },
        },
        {
          title: '类型',
          name: 'type',
          type: 'select',
          optionList: [],
          tipMap: {},
          tagStyle: {},
          showValue: false,
          change: (data) => {
            switch (data.type) {
              //判断题
              case 2:
                data.options = data.options.slice(0, 2)
              // 单选题
              case 0:
                //清空选项
                data.options.forEach((v) => {
                  v.isAnswer = false
                })
                // 默认选中第一个
                data.options[0].isAnswer = true
                break
            }
          },
        },
        {
          title: '答案',
          name: 'answer',
          type: 'custom_answer',
          hidden: {
            header: true,
          },
        },
        {
          title: '解析',
          name: 'parse',
          type: 'markdown',
          hidden: {
            header: true,
          },
        },
      ],
      //试题查询路径
      problemSelectUrl: 'problem/lookProblem',
      //试题新增路径
      problemInsertUrl: 'problem/addOneProblem',
      //试题更新路径
      problemUpdateUrl: 'problem/updateOneProblem',
      //试题删除路径
      problemDeleteUrl: 'problem/deleteProblems',
      //试题详情路径
      problemDetailUrl: 'problem/lookProblemById',
      //试题导出路径
      problemExportUrl: '/examService/pro/export',
      //试题导入路径
      problemImportUrl: '/examService/pro/import',
      //表格列
      problemTableColumns: [
        {
          title: '试题内容',
          name: 'content',
          width: 120,
        },
        {
          title: '分数',
          name: 'score',
          width: 110,
        },
        {
          title: '类型',
          name: 'type',
          type: 'tag',
          width: 100,
          tagStyle: {},
          filters: [],
          tipMap: {},
        },
        {
          title: '科目',
          name: 'subjectName',
          width: 110,
          filters: [],
          filterName: 'name',
        },
        {
          title: '所属题库',
          name: 'bankName',
          width: 120,
        },
        {
          title: '创建时间',
          name: 'createTime',
          width: 180,
        },
        {
          title: '修改时间',
          name: 'updateTime',
          width: 180,
        },
      ],
      //表单按钮控制
      problemFormButtonCtl: {},
      //表单校验
      problemFormRules: {
        name: [
          {
            required: true,
            message: '试题名不得为空!',
            trigger: 'blur',
          },
        ],
      },
      //类型数据
      typeMap: {
        filters: [
          { title: '单选题', name: 0 },
          { title: '多选题', name: 1 },
          { title: '判断题', name: 2 },
          { title: '主观题', name: 3 },
        ],
        style: {
          0: 'primary',
          1: 'success',
          2: 'warning',
          3: 'danger',
        },
        tipMap: {
          0: '单选题',
          1: '多选题',
          2: '判断题',
          3: '主观题',
        },
      },
      //表单校验
      problemFormRules: {
        content: [
          {
            required: true,
            message: '试题内容不得为空!',
            trigger: 'blur',
          },
        ],
        score: [
          {
            required: true,
            message: '分数不得为空!',
            trigger: 'change',
          },
          {
            type: 'number',
            message: '分数必须为数字!',
            trigger: 'change',
          },
        ],
        answer: [
          {
            required: true,
            message: '答案不得为空!',
            trigger: 'blur',
          },
        ],
        parse: [
          {
            required: true,
            message: '解析不得为空!',
            trigger: 'blur',
          },
        ],
        subjectId: [
          {
            required: true,
            message: '科目不得为空!',
            trigger: 'change',
          },
        ],
        bankId: [
          {
            required: true,
            message: '题库不得为空!',
            trigger: 'change',
          },
        ],
        type: [
          {
            required: true,
            message: '类型不得为空!',
            trigger: 'change',
          },
        ],
        option: [
          {
            required: true,
            message: '选项内容不得为空!',
            trigger: 'blur',
          },
        ],
      },
      //题目选项答案数量
      currentOptionSize: 1,
    }
  },

  mounted() {
    //下拉框数据注入
    this.$set(this.problemFormList[6], 'optionList', this.typeMap.filters)
    //标签
    this.$set(this.problemFormList[6], 'tipMap', this.typeMap.tipMap)
    //标签样式
    this.$set(this.problemFormList[6], 'tagStyle', this.typeMap.style)
    //表格筛选
    this.$set(this.problemTableColumns[2], 'filters', this.typeMap.filters)
    //标签样式
    this.$set(this.problemTableColumns[2], 'tagStyle', this.typeMap.style)
    //提示
    this.$set(this.problemTableColumns[2], 'tipMap', this.typeMap.tipMap)
  },
  created() {
    this.initSubjectData()
    this.initBankData()
  },
  methods: {
    initSubjectData() {
      this.$store.dispatch('subject/lookSubjectAll').then((response) => {
        this.problemFormList[5].optionList = this.problemTableColumns[3].filters = response.data
      })
    },
    initBankData() {
      this.$store.dispatch('problemBank/lookAllProblemBank').then((response) => {
        this.problemFormList[3].optionList = this.problemTableColumns[4].filters = response.data.map((v) => {
          return { title: v.name, name: v.id }
        })
      })
    },
    //初始化表单数据(将选项信息填充到表单数据中)
    initData(type, data) {
      if (type == '新增') {
        this.$set(data, 'options', [
          {
            index: 'A',
            content: undefined,
            isAnswer: true,
          },
          {
            index: 'B',
            content: undefined,
            isAnswer: false,
          },
          {
            index: 'C',
            content: undefined,
            isAnswer: false,
          },
          {
            index: 'D',
            content: undefined,
            isAnswer: false,
          },
        ])
      } else if (type == '修改') {
        this.$store.dispatch(this.problemDetailUrl, data).then((response) => {
          //初始化表单数据
          this.$set(data, 'options', response.data.options)
        })
      }
    },
    // 添加选项
    addOption(item) {
      if (item.type == 2 && item.options.length >= 2) {
        return
      }
      item.options.push({
        index: String.fromCharCode(65 + item.options.length),
        option: '',
        isAnswer: false,
      })
    },
    // 删除选项
    deleteOption(index, item) {
      item.options.splice(index, 1)
      // 重新排序
      item.options.forEach((v, i) => {
        v.index = String.fromCharCode(65 + i)
      })
    },
    // 选项改变
    optionChange(option, item) {
      //单选与判断
      if ((item.type == 0 || item.type == 2) && this.currentOptionSize >= 1) {
        option.isAnswer = false
      }
      this.currentOptionSize = item.options.filter((v) => v.isAnswer).length
    },
    //下载文件
    downloadFile,
    //markdown上传文件
    markdownUploadFile(event, insertImage, files) {
      if (files == null || files.length < 1) {
        return
      }
      this.$store.dispatch('file/uploadFile', files[0]).then((response) => {
        if (response.success) {
          insertImage({
            url: this.downloadFile(response.data),
            desc: response.data,
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep.success_answer {
  .el-input__inner {
    color: #67c23a;
    border: #67c23a 1px solid;
    width: 50%;
  }
}
::v-deep .error_answer {
  .el-input__inner {
    color: #f56c6c;
    border: #f56c6c 1px solid;
    width: 50%;
  }
}
</style>
